import Dialog from './dialog';
import scroller from './scroller';
import tplWcjj from '../_tpl/form_wcjj.ejs';
import tplNoctice from '../_tpl/form_notice.ejs';
import tplCompany from '../_tpl/form_company.ejs';
import tplSingle from '../_tpl/form_single.ejs';
import tplResult from '../_tpl/form_result.ejs';

let $apply;
let applySwiper;
let openDialog = false;
let dialogCompany, dialogSingle, dialogWcjj, dialogNotice, dialogResult;

let pending = {
    company: false,
    wcjj: false,
    single: false
};
let years = [];

function init() {
    $apply = $('#section-apply');

    applySwiper = new Swiper('#swiper-apply', {
        // loop: true,
        simulateTouch: false,
        pagination: {
            el: '.swiper-pagination',
            clickable: true
        },
        autoplay: {
            delay: 3000,
            disableOnInteraction: false
        }
    });

    $apply.find('.content-scroller').each((i, el) => scroller(el));

    let myScroller, companyScroller, singleScroller;

    $.get('/c/Apply/getRecentYear', res => {
        years = res.year;
        $('#dialog-company')
            .find('.company-scroller')
            .append(tplCompany({ years }));
        $('#dialog-single')
            .find('.single-scroller')
            .append(tplSingle({ years }));

        dialogCompany = new Dialog('#dialog-company', {
            onClose: () => {
                closeAndStart();
                $('#company-form').remove();
            },
            onOpen: () => {
                openAndStop();
                dialogCompany.$el
                    .find('.z-scroller-content')
                    .append(tplCompany({ years }));
                if (!companyScroller)
                    setTimeout(() => {
                        companyScroller = scroller(
                            '#section-apply .company-scroller'
                        );
                    });
            }
        });

        dialogSingle = new Dialog('#dialog-single', {
            onClose: () => {
                closeAndStart();
                $('#single-form').remove();
            },
            onOpen: () => {
                openAndStop();
                dialogSingle.$el
                    .find('.z-scroller-content')
                    .append(tplSingle({ years }));
                if (!singleScroller)
                    setTimeout(() => {
                        singleScroller = scroller(
                            '#section-apply .single-scroller'
                        );
                    });
            }
        });
    });

    dialogWcjj = new Dialog('#dialog-wcjj', {
        onClose: () => {
            closeAndStart();
            $('#wcjj-form').remove();
            dialogWcjj.$el.find('.dialog-body').append(tplWcjj());
        },
        onOpen: openAndStop
    });

    dialogNotice = new Dialog('#dialog-notice', {
        onClose: () => {
            closeAndStart();
            $('.notice-content').remove();
            dialogNotice.$el.find('.z-scroller-content').append(tplNoctice());
        },
        onOpen: () => {
            openAndStop();
            if (!myScroller)
                myScroller = scroller('#section-apply .notice-scroller');
        }
    });

    dialogResult = new Dialog('#dialog-result', {
        onClose: () => {
            closeAndStart();
            $('.result-box').remove();
            dialogResult.$el.find('.dialog-body').append(tplResult());
        },
        onOpen: openAndStop
    });

    $apply
        .on('click', '.query-btn', query)
        .on('click', '.captha-img', getCaptha)
        .on('change', '.upload input[type=file]', dealFile)
        .on('mouseover', '.detail', () => applySwiper.autoplay.stop())
        .on(
            'mouseout',
            '.detail',
            () => !openDialog && applySwiper.autoplay.start()
        )
        .on('click', '.wct-btn img', () => {
            location.href = "/apply/guide";
        })
        .on('click', '.result-btn', () => {
            dialogNotice.close();
            dialogResult.open();
        })
        .on('click', '.apply-btn', handleClickApply)
        .on('click', '.wcjj-btn', () => dialogWcjj.open())
        .on('click', '[name=if500or50]', e => {
            if ($(e.target).val() === '是') {
                $('.default-hidden').show();
            } else {
                $('.default-hidden').hide();
            }
        });

    $apply.on('change', '#wcjj-shu', function () {
        const file = this.files[0];
        $apply.find('.file-desc span').text(`已选择文件：${file.name}`);
    });

    $apply.on('click', '.wcjj-submit', submitWcjj);
    $apply.on('click', '.company-btn', submitCompany);
    $apply.on('click', '.single-btn', submitSingle);
}

function openAndStop() {
    openDialog = true;
    applySwiper.autoplay.stop();
}

function closeAndStart() {
    openDialog = false;
    applySwiper.autoplay.start();
}

function query() {
    $.ajax({
        type: 'POST',
        url: '/c/Apply/searchInstitutionCreditCode',
        data: $(this)
            .parents('form')
            .serialize(),
        success: res => {
            const { tips } = res;
            $(this)
                .parents('form')
                .next()
                .show()
                .next()
                .show()
                .html(tips);
        },
        error: xhr => alert(xhr.responseText)
    });
}

function handleClickApply() {
    if (!$apply.find('[name=accept]').prop('checked')) {
        alert('请阅读申请须知并同意');
        return;
    }
    const value = $apply.find('[name=apply-type]:checked').val();
    if (!value) {
        alert('请选择申请类型');
        return;
    }
    dialogNotice.close();
    if (value === 'company') dialogCompany.open();
    if (value === 'single') dialogSingle.open();
}

function submitWcjj() {
    if (pending.wcjj) return;
    pending.wcjj = true;
    const text = $(this).text();
    $(this).text('处理中。。。');
    const data = new FormData(document.querySelector('.wcjj-form'));
    $.ajax({
        type: 'POST',
        url: '/c/Apply/addFund',
        processData: false,
        contentType: false,
        data,
        success: res => {
            alert(res);
            dialogWcjj.close();
        },
        error: err => {
            if (err.status === 413) {
                alert('提交失败，文件不能超过60M！');
            } else {
                alert(err.responseText);
            }
            $(this).text(text);
            getCaptha.call($('.captha-img'));
        },
        complete: () => {
            pending.wcjj = false;
        }
    });
}

function submitCompany() {
    if (pending.company) return;
    pending.company = true;
    const text = $(this).text();
    $(this).text('处理中。。。');
    const data = new FormData(document.getElementById('company-form'));
    if (data.get('if500or50') === '是') {
        const ysr = data.getAll('ysr');
        const lr = data.getAll('lr');
        data.append(
            'yearMoneys',
            JSON.stringify(
                years.map((year, i) => ({
                    year,
                    ysr: ysr[i],
                    lr: lr[i]
                }))
            )
        );
    } else {
        data.delete('qishiJse');
        data.delete('sndJse');
    }
    data.delete('ysr');
    data.delete('lr');
    data.delete('year');

    $.ajax({
        type: 'POST',
        url: '/c/Apply/addLoanByCompany',
        processData: false,
        contentType: false,
        data,
        success: res => {
            alert(res);
            dialogCompany.close();
        },
        error: err => {
            if (err.status === 413) {
                alert('提交失败，文件不能超过60M！');
                return;
            }
            alert(err.responseText);
            $(this).text(text);
        },
        complete: () => {
            pending.company = false;
        }
    });
}

function submitSingle() {
    if (pending.single) return;
    pending.single = true;
    const text = $(this).text();
    $(this).text('处理中。。。');
    const data = new FormData(document.getElementById('single-form'));
    if (data.get('if500or50') === '是') {
        const ysr = data.getAll('ysr');
        const lr = data.getAll('lr');
        data.append(
            'yearMoneys',
            JSON.stringify(
                years.map((year, i) => ({
                    year,
                    ysr: ysr[i],
                    lr: lr[i]
                }))
            )
        );
    } else {
        data.delete('qishiJse');
        data.delete('sndJse');
    }
    data.delete('ysr');
    data.delete('lr');
    data.delete('year');
    $.ajax({
        type: 'POST',
        url: '/c/Apply/addLoanByPerson',
        processData: false,
        contentType: false,
        data,
        success: res => {
            alert(res);
            dialogSingle.close();
        },
        error: err => {
            if (err.status === 413) {
                alert('提交失败，文件不能超过60M！');
                return;
            }
            alert(err.responseText);
            $(this).text(text);
        },
        complete: () => {
            pending.single = false;
        }
    });
}

function getCaptha() {
    const img = new Image();
    img.addEventListener('load', function () { });
    img.src = `/c/Apply/captha?qq=${Date.now()}`;
    $(this).attr('src', img.src);
}

function dealFile() {
    const $el = $(this);
    const file = this.files[0];
    const type = file.type.split('/')[0];

    if (type === 'image') {
        $el.parent()
            .find('.upload-desc')
            .text('');
        const reader = new FileReader();
        reader.addEventListener('load', () => {
            $el.parents(
                '.upload'
            )[0].style.backgroundImage = `url(${reader.result})`;
        });
        reader.readAsDataURL(file);
    } else {
        $el.parents('.upload')[0].style.backgroundImage = 'none';
        $el.parent()
            .find('.upload-desc')
            .text(file.name);
    }
}

export default init;
